<!-- Login  -->
<template>
  <div class="app_contain">
    <div class="contain">
      <header></header>
      <div class="center">
        <div class="login_card">
          <img src="@/assets/img/logo.svg" alt="logo" />
          <!-- 密码登录 -->
          <el-tabs
            v-model="activeName"
            @tab-click="handleClick"
            stretch="stretch"
          >
            <el-tab-pane label="密码登录" name="loginByPassword">
              <el-input placeholder="请输入账号" v-model="loginForm.username">
                <template slot="prepend">账号</template>
              </el-input>
              <el-input
                placeholder="请输入密码"
                v-model="loginForm.password"
                hidden
                autocomplete="new-password"
                show-password
              >
                <template slot="prepend">密码</template>
              </el-input>
            </el-tab-pane>
            <!-- 短信登录 -->
            <el-tab-pane label="短信登录" name="loginBySms">
              <el-input placeholder="请输入账号" v-model="loginForm.username">
                <template slot="prepend">手机号</template>
              </el-input>
              <el-input
                placeholder="请输入密码"
                v-model="captcha"
                hidden
                autocomplete="new-password"
              >
                <template slot="prepend">验证码</template>
              </el-input>
              <el-button
                type="primary"
                plain
                @click="send_captcha"
                style="margin-top: 10px"
                :disabled="isDisabled"
                >{{ buttonName }}</el-button
              >
            </el-tab-pane>
          </el-tabs>

          <el-link
            type="primary"
            class="forget_password"
            @click="to_forget_password"
            >忘记密码</el-link
          >

          <div class="login_btn_contain" @click="Login">登录</div>
        </div>
        <div class="register">
          <span>没有账号？</span>
          <el-link type="primary" @click="toregister">立即加入</el-link>
        </div>
      </div>
      <footer></footer>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      CountDown: 60,
      buttonName: "发送验证码",
      isDisabled: false,
      loginForm: {
        username: "",
        password: "",
      },
      captcha: "",
      captcha_id: "",
      activeName: "loginByPassword",
      stretch: true,
      check_account_phone:
        /^(13[0-9]|14[5|7]|15[0|1|2|3|4|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$/,
      check_account_email: /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/,
      redirect: undefined,
    };
  },
  methods: {
    send_captcha() {
      if (this.check_account_phone.test(this.loginForm.username)) {
        //先把按钮禁止，并进行倒计时，防止网速慢的用户重复点击
        this.isDisabled = true;
        let timerId = setInterval(() => {
          this.CountDown--;
          this.buttonName = this.CountDown + "秒后重试";
          if (this.CountDown <= 0) {
            clearInterval(timerId);
            this.buttonName = "重新发送";
            this.CountDown = 60;
            this.isDisabled = false;
          }
        }, 1000);
        //操作验证发送API BLOCK
        this.$store
          .dispatch("login/sms", this.loginForm.username)
          .then((data) => {
            this.$message.success(data);
          })
          .catch((error) => {
            // this.$message.error("验证码发送失败，请重试");
            clearInterval(timerId);
            this.buttonName = "重新发送";
            this.CountDown = 60;
            this.isDisabled = false;
          });
      } else {
        this.$message.warning("手机格式不对");
      }
    },
    handleClick(tab, event) {
      console.log(tab, event);
    },
    Login() {
      if (!this.loginForm.username) {
        this.$message.warning("请输入账号");
      } else {
        //当账号输入，并且为密码登录时
        if (this.activeName === "loginByPassword") {
          if (!this.loginForm.password) {
            this.$message.warning("请输入密码");
          } else {
            this.$store.dispatch("login/Login", this.loginForm).then((data) => {
              console.log(data);
              this.$message.success("登录成功");
              if (data === "ADMIN") {
                this.$router.push({ path: this.redirect || "/admin" });
              } else {
                this.$router.push({ path: this.redirect || "/" });
              }
            });
          }
        } else {
          // 当账号存在，并为验证码登录时
          // account, captcha, captcha_id
          if (this.captcha) {
            const userInfo = {
              account: this.loginForm.username,
              captcha: this.captcha,
              captcha_id: this.$store.state.login.captcha_id,
            };
            this.$store
              .dispatch("login/login_bycaptcha", userInfo)
              .then((data) => {
                this.$message.success("登录成功");
                if (data === "ADMIN") {
                  this.$router.push("/admin");
                } else {
                  this.$router.push("/");
                }
              });
          } else {
            this.$message.warning("请输入验证码");
          }
        }
      }
    },
    toregister() {
      this.$router.push("/register");
    },
    to_forget_password() {
      this.$router.push("/forget_password");
    },
  },
  mounted() {},
  watch: {
    $route: {
      handler: function (route) {
        this.redirect = route.query && route.query.redirect;
      },
      immediate: true,
    },
  },
  created() {
    if (sessionStorage.getItem("login_countdown_info")) {
      this.CountDown = JSON.parse(
        sessionStorage.getItem("login_countdown_info")
      ).CountDown;
      this.isDisabled = JSON.parse(
        sessionStorage.getItem("login_countdown_info")
      ).isDisabled;
      this.captcha_id = JSON.parse(
        sessionStorage.getItem("login_countdown_info")
      ).captcha_id;
      //防止未知BUG
      let activeName = JSON.parse(
        sessionStorage.getItem("login_countdown_info")
      ).activeName;
      if (activeName) {
        this.activeName = activeName;
      }
      this.$store.state.login.captcha_id = this.captcha_id;
    }
    //进入该页面时，若倒计时还在进行，则继续跑倒计时
    if (this.isDisabled) {
      let timerId = setInterval(() => {
        this.CountDown--;
        this.buttonName = this.CountDown + "秒后重试";
        if (this.CountDown <= 0) {
          clearInterval(timerId);
          this.buttonName = "重新发送";
          this.CountDown = 60;
          this.isDisabled = false;
        }
      }, 1000);
    }

    window.addEventListener("beforeunload", () => {
      sessionStorage.setItem(
        "login_countdown_info",
        JSON.stringify({
          CountDown: this.CountDown,
          isDisabled: this.isDisabled,
          captcha_id: this.$store.state.login.captcha_id,
          activeName: this.activeName,
        })
      );
    });
  },
  beforeRouteLeave(to, from, next) {
    /*
      隶属于 Vue-Router
      to:router 即将要进入的路由对象
      from:router  当前导航正要离开的路由
      next()进行管道中的下一个钩子
      最后要确保调用next方法，否则钩子不会被resolved
    */
    sessionStorage.setItem(
      "login_countdown_info",
      JSON.stringify({
        CountDown: this.CountDown,
        isDisabled: this.isDisabled,
        captcha_id: this.$store.state.login.captcha_id,
        activeName: this.activeName,
      })
    );
    next();
  },
};
</script>

<style lang='scss' scoped>
@import "@/assets/css/login.scss";
</style>